package cn.itsource.ymcc.consumer;

import cn.itsource.ymcc.constant.Constants;
import cn.itsource.ymcc.constant.PayConstants;
import cn.itsource.ymcc.constant.RConst;
import cn.itsource.ymcc.domain.CourseOrder;
import cn.itsource.ymcc.exception.GlobalException;
import cn.itsource.ymcc.mapper.CourseOrderMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;

@Component
@RocketMQMessageListener(consumerGroup = "service-order-timeout-consumer",
        //Topic
        topic = PayConstants.MQ_TOPIC_PAYORDER_TIMEOUT_PAYORDER,
         //TAGS
        selectorExpression = PayConstants.MQ_TAGS_PAYORDER_TIMEOUT_PAYORDER
)
@Slf4j
public class CourseTimeOutConsumer implements RocketMQListener<MessageExt> {

    @Autowired
    private CourseOrderMapper courseOrderMapper;
    @Override
    public void onMessage(MessageExt message) {

        try {
            byte[] body = message.getBody();
            String bodyStr = new String(body, Constants.UTF8);
            CourseOrder courseOrder = courseOrderMapper.selectOne(new LambdaQueryWrapper<CourseOrder>().eq(CourseOrder::getOrderNo, bodyStr));
            courseOrder.setStatusOrder(RConst.Num.INT_2);
            courseOrderMapper.updateById(courseOrder);
            System.out.println("课程订单超时更改状态成功");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            //通过异常来决定ACK
            throw new GlobalException("课程订单超时更改状态失败");
        }
    }
}